package com.itheima.demo1creat;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadDemo3
{
    public static void main(String[] args) {
        //用callable接口来创建多线程
        MyCallable c=new MyCallable(5);
        //用FutureTask来接收callable接口返回的结果
        FutureTask<Integer> ft = new FutureTask<>(c);
        //把FutureTask接口对象交给线程对象来调用
        Thread t1 = new Thread(ft);
        //执行
        t1.start();
        //获取结果
         try
             {
                 //如果主线程没有执行完毕的时候 会让出CPU资源 让其它线程执行
                 System.out.println(ft.get());
             }
             catch (Exception e)
             {
                 e.printStackTrace();
             }
    }
}
class MyCallable implements Callable<Integer>
{
    private int n;
    public MyCallable(int n)
    {
        this.n =n;
    }
    public MyCallable() {}
    public Integer call() throws Exception
    {
        int sum=0;
        for (int i = 0; i < n; i++)
        {
            sum+=i;
        }
        return sum;
    }
}
